/*
 * --------------------------------------
 * Functions that manipulates the objects
 * CRUD, Search
 * --------------------------------------
 */

var sortBy = 'distance'; // default value

var things = []; // "Things" array, contains all the "thing" objects

/*
 *  Get data from the bdd in a JSON format
 * 
 */
function getData() {
	if(param == 'm')
	{
		url = 'object/get_things/m';
	}
	else
	{
		url = 'object/get_things';
	}
	$.ajax({
		type: 'GET',
		url: url,
		timeout: 3000,
		success: function(data)
		{
			display_alert('list updated', '#alert_area', 'success');
			updateThings(data);
			//debugThings();
			refreshList(sortBy);
			displayOnMap();
		},
        error: function() { display_alert('connexion problem', '#alert_area', 'error'); }
	});
	switchInterface('content');
}

/*
 *  Empty and update the array Things from a JSON format
 *  data : JSON format
 */
function updateThings(data)
{
	things = []; // make sure we reset the array
	
	$.each(data, function(index, array) // create the array, index count the iterations, array is the content
	{
		var id = array['id'];
		var thing = new Thing(array); // create a "thing" and give it the array with the content
		things[id] = thing; // the associative array "things" collects all the things by id
	});
}

function debugThings()
{
	$('#debuglive').html('<p>'+mapCenter+'</p>');
	$('#debug').empty();
	$('#debug').append('<p>---- debug ----</p>');
	for(i in things)
  	{
		var txt = '<p>uid : '+things[i].uid+'<br/>' +
				  'id : '+things[i].id+'<br/>' +
	  			  'title : '+things[i].title+'<br/>' +
	  			  'lat : '+things[i].lat+'<br/>' +
	  			  'lng : '+things[i].lng+'<br/>' +
	  			  'distance : '+things[i].distance+'<br/>';
	  			  '-----------------------</p>';
		$('#debug').append(txt);
	}
}

/*
 *  Create an object
 */

var imgURL = new Array();
var fileCount = 0;

function init_object_create(manualuploader) {
		if(fileCount > '0')
		{
			manualuploader.fineUploader('uploadStoredFiles');
		}
		else
		{
			object_create();
		}
}


function object_create() {
	
	//debugger;
	var title = $('#title').val();
    var price = $('#price').val();
    var description = $('#description').val();
    var lat = registrationMarker.getLatLng().lat;
    var lng = registrationMarker.getLatLng().lng;
    var terms = $('#terms').val();
    
    //if(imgURL.length === 0)
    if(imgURL == null)
    	{ imgURL = 'empty'; }
    else
    	{ imgURL = imgURL.toString(); }

	$.ajax({
		type: 'POST',
		url: 'object/create',
		data: {'title': title, 'description': description, 'price': price, 'lat': lat, 'lng': lng, 'terms' : terms, 'imgURL': imgURL},
		timeout: 3000,
		success: function(data) {
			if(data == 'success')
			{
				getData();
				registrationMarker.closePopup();
	    		registrationLayer.clearLayers();
	    		cancelRegistration();
	    		display_alert('The item has been added', '#alert_area', 'success');
			}
			else if(data == 'fail_login')
			{
				display_alert('You must be logged to add an item', '#alert_area', 'error');
			}
			else if(data == 'fail_form')
			{
				display_alert('You wrote something wrong', '#alert_area', 'error');
			}
			else
			{
				display_alert('The item hasn\'t been added', '#alert_area', 'error');
			}
		},
        error: function() { display_alert('connexion problem', '#alert_area', 'error'); }
	});
	
	// reset the array containing the url of the uploaded picture
	imgURL.length = 0;
	//imgURL = null;
}

function initRegistration() {
    map.addEventListener('click', onMapClick);
    document.body.style.cursor = 'crosshair';
    $('#add_object_button').html('Cancel');
    $("#content").prepend('<div id="register_area" class="well">Choose a location on the map</div>');
    //$("#main_header").hide();
    $("#search_object").hide();
    $("#main_content").hide();
    return false;
}

function cancelRegistration() {
    document.body.style.cursor = 'default';
    map.removeEventListener('click', onMapClick);
    $('#add_object_button').html('Add an object');
    registrationMarker.closePopup();
    registrationLayer.clearLayers();
    firstClick = true;
    $("#register_area").hide();
    $("#main_header").show();
    $("#main_content").show();
    display_alert('registration has been canceled', '#alert_area', 'error');
}

/*
 *Update object 
 */

function init_update(thing_id) {

	var thing = things[thing_id];
	
	// leaflet
	cancel_onMoveEnd();
	if(thing.marker != null)
	{
		thing.marker.unbindPopup();
		thing.marker.bindPopup('You can now move your object!').openPopup();
		thing.marker.dragging.enable();
	}
	//debugger;
	//display the form
	msg = '<img class="photo img-polaroid" src="assets/uploads/'+displayPhoto(thing.uid, thing.imgURL)+'">'
	+ '<form id="form_object_update" method="post" accept-charset="utf-8" >'
	+ '	<label>Title</label><input type="text" id="title" name="title" value="'+thing.title+'" size="30" onfocus="javascript: this.select();return false;"/>'
	+ '	<label>Price</label><input type="text" id="price" name="price" value="'+thing.price+'" size="30" onfocus="javascript: this.select();return false;" />' 
	+ '	<label>Description</label><textarea id="description" name="description" onfocus="javascript: this.select();return false;">'+thing.description+' </textarea><br/>'
	+ ' 	<button type="submit" class="btn btn-primary" onclick="object_update('+thing.id+');return false;">Save changes</button>'
	+ ' 	<button type="button" class="btn" onclick="cancel_update('+thing.id+');return false;">Cancel</button>'
	+ '</form>';
	
	$('#'+thing.id).html(msg);
	 return false;
};

function cancel_update(thing_id)
{
	var thing = things[thing_id];
	
	// leaflet
	init_onMoveEnd();
	
	thing.marker.closePopup();
	thing.marker.dragging.disable();
	
	refreshList('distance');
}

function object_update(thing_id) {
	
	// get the object
	var thing = things[thing_id];
	
	//debugger;
	var title = $('#title').val();
    var price = $('#price').val();
    var description = $('#description').val();
    var lat = thing.marker.getLatLng().lat;
    var lng = thing.marker.getLatLng().lng;
    /*var lat = registrationMarker.getLatLng().lat;
    var lng = registrationMarker.getLatLng().lng;*/
    
    //if(imgURL.length === 0)
    if(imgURL == null)
    	{ imgURL = 'empty'; }
    else
    	{ imgURL = imgURL.toString(); }

	$.ajax({
		type: 'POST',
		url: 'object/update',
		data: {'id' : thing_id, 'title': title, 'description': description, 'price': price, 'lat': lat, 'lng': lng, 'imgURL': imgURL},
		timeout: 3000,
		success: function(data) {
			if(data == 'success')
			{
				getData();
				/*registrationMarker.closePopup();
	    		registrationLayer.clearLayers();*/
	    		cancelRegistration();
	    		display_alert('The item has been added', '#alert_area', 'success');
	    		
			}
			else if(data == 'fail_login')
			{
				display_alert('You must be logged to add an item', '#alert_area', 'error');
			}
			else if(data == 'fail_form')
			{
				display_alert('You wrote something wrong', '#alert_area', 'error');
			}
			else
			{
				display_alert('The item hasn\'t been added', '#alert_area', 'error');
			}
		},
        error: function() { display_alert('connexion problem', '#alert_area', 'error'); }
	});
	
	// reset the array containing the url of the uploaded picture
	imgURL.length = 0;
}

/*
 * Delete an object
 */

function set_delete(thing_id)
{
	$('#'+ thing_id).attr('status', 'delete');
}

function init_delete()
{
	$('[status="delete"]').each(function(i, e) {
		object_delete($(e).attr('id'));
	});
}

function object_delete(id)
{
	$.ajax({
		type: 'GET',
		url: 'object/delete/'+id,
		timeout: 3000,
		success: function(data) {
		if(data == 'success')
		{
			display_alert('the item has been deleted', '#alert_area', 'success');
			getData();
			refreshList(sortBy);
		}
		else
		{
			display_alert('the item hasn\'t been deleted', '#alert_area', 'error');
		}
	},
        error: function() { display_alert('connexion problem', '#alert_area', 'error'); }
	});
}

/*
 *  Update an object
 */


/*
 * Search an object
 */



function object_search(string) {
	
	if(param == 'm')
	{
		domElem = '#mobject_list';
	}
	else
	{
		domElem = '#object_list';
	}
	
	
	$.ajax({
		type: 'POST',
		url: 'object/search',
		data: {'string': string, 'param': param},
		timeout: 3000,
		success: function(data) {
			$(domElem).empty();
			if(!jQuery.isEmptyObject(data) && data != 'fail_form')
	    	{
				updateThings(data);
				refreshList(sortBy);
				displayOnMap;
	    	}
	    	else
	    	{
	    		$(domElem).html('not found...');
	    	}
		},
        error: function(data) { display_alert('connexion problem', '#alert_area', 'error'); }
	});
}

/*
 * Refresh the object list
 * 
 * mapCenter: actual position of the user - array [lat, lng]
 * sortBy : kind of sorting distance or price
 */

var mapCenter = new L.LatLng(0,0); // to calculate at any time the distance in refreshListBy...

function displayThing(thing)
{
	var msg = '<div class="object">'
	+ '<div id="' + thing.id + '" class="object_info" onclick="locate(' + thing.id + ');">'
		+ '<img class="photo img-polaroid" src="assets/uploads/'+displayPhoto(thing.uid, thing.imgURL)+'">'
		+ '<strong>' + thing.title + '</strong><br/>'
		+ 'Image <img src="https://graph.facebook.com/gauthier.vdp/picture"/>';
		if(param != 'm')
		{
			msg += ' by ' + thing.uid + '<br />';
		}
		msg += '' + thing.description + '<br />'
		//+ ' : ' + thing.price + ' euros<br />
		+ '<span class="distance">' + displayDistance(thing.distance) + '</span> away - '
		+ displayDate(thing.added) + ' ago'
	+ '</div>';
	if(param == 'm')
	{
		msg += '<div class="object_menu">'
		+ '<span onclick="locate('+ thing.id +');"><i class="icon-screenshot"></i> locate</span><br/>'
		+ '<span onClick="set_delete(' + thing.id + ');" data-toggle="modal" data-target="#confirmationModal"><i class="icon-remove"></i> delete</span><br/>'
		+ '<span onclick="init_update('+thing.id+');locate('+ thing.id +')"><i class="icon-edit"></i> updates</span>'
		+ '</div>';
	}
	msg += '<div class="clearfix"></div>'
	+ '</div>';

	return msg;
}

function displayDistance(distance)
{
	var type = 'm';
	
	if(distance >= 1000)
	{
		distance /= 1000;
		type = 'km'; 
	}
	
	distance = Math.round(distance);
	
	if(type == 'km')
	{
		distance+= ' km';
	}
	else
	{
		distance+= ' m';
	}
	
	return distance;
}

function displayPhoto(uid, imgURL)
{
	var array = imgURL.split(',');
	if(array[0] == 'empty')
		{
			imgURL = 'nophoto.png';
		}
	else
		{
			imgURL = uid+'/'+array[0];
		}
	return imgURL;
}

function displayDate(datetime)
{
	
	return datetime;
}

function refreshDistance()
{
	// select the list to update
	if(param == 'm')
	{
		selector = '#mobject_list';
	}
	else
	{
		selector = '#object_list';
	}
	
	
}

function refreshList(sortBy)
{
	
	if(param == 'm')
	{
		selector = '#mobject_list';
	}
	else
	{
		selector = '#object_list';
	}
	set_height(selector);
	
	if(sortBy == 'distance')
	{
		refreshListByDistance(selector);
	}
	if(sortBy == 'price')
	{
		refreshListByPrice(selector);
	}
	displayOnMap();
}

function refreshListByDistance(selector)
{
	sortBy = 'distance';
	
	var array = [];
	
	for(i in things)
	{
		things[i].setDistance(mapCenter);
		array.push([things[i], things[i].distance]);
	}	
	array.sort(function(a,b) { return a[1] - b[1]; });
	//things.length = 0; // empty the array things, we cannot sort an "associative" array
	//things = [];
	
	$(selector).empty();
	
	//var distCounter = 0;
	
	
	var out_of_map_display=false;
	
	for(var i=0;i<array.length;i++)
	{
		var thing = array[i][0];		
		
		/*if(thing.distance < evalDistance() || param == 'm')
		
		{
			if(thing.distance>200 && thing.distance<500 && distCounter<200 && i!=0)
			{
				$(selector).append('<div class="division"><strong>- 200 m</strong></div>');
				distCounter = 200;
			}
			if(thing.distance>500 && thing.distance<evalDistance() && distCounter<500 && i!=0)
			{
				$(selector).append('<div class="division"><strong>- 500 m</strong></div>');
				distCounter = 500;
			}		
			
			var msg = displayThing(thing, param);
			$(selector).append(msg);
		}*/
		
	
		bounds=map.getBounds();		
	
			if (!bounds.contains(thing.latlng) && out_of_map_display==false) //The object is within the bounds map.
			{				
				$(selector).append('<div class="division"><strong>OUT OF MAP</strong></div>');	
				out_of_map_display=true;
			}			
			var msg = displayThing(thing, param);
			$(selector).append(msg);
			
			
		//things[array[i][0].id] = array[i][0]; // repopulate the things array
	}
	//$(selector).append('<div class="division"><strong>- '+displayDistance(evalDistance())+'</strong></div>');
}

function refreshListByPrice(selector)
{
	sortBy = 'price';
	
	var array = [];
	
	for(i in things)
	{
		things[i].setDistance(mapCenter);
		array.push([things[i], things[i].price]);
	}
	
	array.sort(function(a,b) { return a[1] - b[1]; });
	
	$(selector).empty();
	
	var priceCounter = 0;
	for(var i=0;i<array.length;i++)
	{
		var thing = array[i][0];
		if(thing.distance < evalDistance() || param == 'm')
		{
			if(thing.price>10 && thing.price<50 && priceCounter<50 && i!=0)
			{
				$(selector).append('<div class="division"><strong>- 10 euros</strong></div>');
				priceCounter = 50;
			}
			if(thing.price>50 && priceCounter<100 && i!=0)
			{
				$(selector).append('<div class="division"><strong>- 50 euros</strong></div>');
				priceCounter = 100;
			}
			
			var msg = displayThing(thing, param);
			$(selector).append(msg);
		}
	}
	$(selector).append('<div class="division"><strong>- '+displayDistance(evalDistance())+'</strong></div>');
}

/*
 *  Not in use
 */